﻿using System;
using System.Collections.Generic; 
using System.Text;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.GZip; 
using System.IO; 
using System.IO.Compression;

    public class GZipUtil
    {

        public static byte[] GZipFile1(string sourcefilename, string zipfilename)
        {
            byte[] rArray = new byte[0]; 
            bool blResult;//表示压缩是否成功的返回结果
            //为源文件创建读取文件的流实例
            FileStream srcFile = File.OpenRead(sourcefilename);
            //为压缩文件创建写入文件的流实例，
            FileStream fs = File.Open(zipfilename, FileMode.Create);
            GZipOutputStream zipFile = new GZipOutputStream(fs);
            try
            {
                byte[] FileData = new byte[srcFile.Length];//创建缓冲数据
                srcFile.Read(FileData, 0, (int)srcFile.Length);//读取源文件
                zipFile.Write(FileData, 0, FileData.Length);//写入压缩文件

                byte[] rsultByteaaaa = new byte[(int)fs.Length];
                fs.Read(rsultByteaaaa, 0, (int)fs.Length);
                rArray = rsultByteaaaa;
                blResult = true;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult = false;
            }
            srcFile.Close();//关闭源文件
            zipFile.Close();//关闭压缩文件
            return rArray;
        }
        
       
       /// <summary>
       /// 使用GZIP压缩文件的方法
       /// </summary>
        /// <param name="sourcefilename">源文件路径</param>
        /// <param name="zipfilename">压缩文件路径</param>
        /// <returns>返回bool操作结果，成功true，失败 flase</returns>
        public static bool GZipFile(string sourcefilename, string zipfilename)
        {
            bool blResult;//表示压缩是否成功的返回结果
            //为源文件创建读取文件的流实例
            FileStream srcFile = File.OpenRead(sourcefilename);
            //为压缩文件创建写入文件的流实例，
            GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipfilename, FileMode.Create));
            try
            {
                byte[] FileData = new byte[srcFile.Length];//创建缓冲数据
                srcFile.Read(FileData, 0, (int)srcFile.Length);//读取源文件
                zipFile.Write(FileData, 0, FileData.Length);//写入压缩文件
                blResult = true;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult = false;
            }
            srcFile.Close();//关闭源文件
            zipFile.Close();//关闭压缩文件
            return blResult;
        }
        /// <summary>
        /// 使用GZIP解压文件的方法
        /// </summary>
        /// <param name="zipfilename">源文件路径</param>
        /// <param name="unzipfilename">解压缩文件路径</param>
        /// <returns>返回bool操作结果，成功true，失败 flase</returns>
        public static bool UnGzipFile(string zipfilename, string unzipfilename)
        {
            bool blResult;//表示解压是否成功的返回结果
            //创建压缩文件的输入流实例
            GZipInputStream zipFile = new GZipInputStream(File.OpenRead(zipfilename));
            //创建目标文件的流
            FileStream destFile = File.Open(unzipfilename, FileMode.Create);
            try
            {
                int buffersize = 2048;//缓冲区的尺寸，一般是2048的倍数
                byte[] FileData = new byte[buffersize];//创建缓冲数据
                while (buffersize > 0)//一直读取到文件末尾
                {
                    buffersize = zipFile.Read(FileData, 0, buffersize);//读取压缩文件数据
                    destFile.Write(FileData, 0, buffersize);//写入目标文件
                }
                blResult = true;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult = false;
            }
            destFile.Close();//关闭目标文件
            zipFile.Close();//关闭压缩文件
            return blResult;
        }
        
         
        public static string GZipFile(string param)
        {
            string rStr = string.Empty; 
            byte[] srcFile = Encoding.UTF8.GetBytes(param);

            MemoryStream ms = new MemoryStream();  
             ICSharpCode.SharpZipLib.Zip.ZipOutputStream zit = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms);
             try
             {
                 zit.Write(srcFile, 0, srcFile.Length);//写入压缩文件 
                 rStr = Convert.ToBase64String(ms.ToArray());
             }
             catch (Exception ee)
             {
                 Console.WriteLine(ee.Message); 
             }
             finally {
                 ms.Close(); 
             } 
            return rStr;
        }


        public static string UnGzipFile(string param)
        {
            string rStr = string.Empty;
            byte[] buffer = Convert.FromBase64String(param); 
             
            MemoryStream ms = new MemoryStream(buffer);

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zit = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(ms);

            StreamReader reader = new StreamReader(zit, System.Text.Encoding.UTF8);
            try
            {
                rStr = reader.ReadToEnd();
            }
            catch (Exception e)
            {
                string a = e.Message;
            } 

            return rStr;
        }



        public static string Compress(string param)
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
            //byte[] data = Convert.FromBase64String(param);
            MemoryStream ms = new MemoryStream();
            Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
            try
            {
                stream.Write(data, 0, data.Length);
            }
            finally
            {
                stream.Close();
                ms.Close();
            }
            return Convert.ToBase64String(ms.ToArray());

        }

        public static string DeCompress(string param)
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
            string rStr = string.Empty;
            MemoryStream ms = new MemoryStream(data);
            Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zit = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(ms);
            StreamReader reader = new StreamReader(sm, System.Text.Encoding.UTF8);

            try
            {
                rStr = reader.ReadToEnd();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                sm.Close();
                ms.Close();
            }
            return rStr;
        }

        public static string DeCompress(byte[] Consure)
        {
            string rStr = string.Empty;
            MemoryStream ms = new MemoryStream(Consure);
            Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zit = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(ms);
            StreamReader reader = new StreamReader(sm, System.Text.Encoding.UTF8);

            try
            {
                rStr = reader.ReadToEnd();
            }
            catch (Exception)
            {

                throw;
            }
            finally {
                sm.Close();
                ms.Close();
            }
            return rStr;
        }

        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="toCompress">需要被压缩的字符串</param>
        /// <returns>返回压缩后的字符串</returns>
        public static string CompressStringToString(string toCompress)
        {
            if (!string.IsNullOrEmpty(toCompress))
            {
                byte[] inBuffer = Encoding.UTF8.GetBytes(toCompress);
                using (MemoryStream compressedStream = new MemoryStream())
                {
                    using (GZipStream gzip = new GZipStream(compressedStream, CompressionMode.Compress, true))
                    {
                        gzip.Write(inBuffer, 0, inBuffer.Length);
                    }

                    compressedStream.Position = 0;

                    // store the length of the uncompressed array (inBuffer) at the first 4 bytes in outBuffer
                    byte[] outBuffer = new byte[compressedStream.Length + 4];
                    System.Buffer.BlockCopy(compressedStream.ToArray(), 0, outBuffer, 4, Convert.ToInt32(compressedStream.Length));
                    System.Buffer.BlockCopy(BitConverter.GetBytes(inBuffer.Length), 0, outBuffer, 0, 4);

                    return Convert.ToBase64String(outBuffer);
                }
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 解压字符串
        /// </summary>
        /// <param name="toDecompress">需要被解压到字符串</param>
        /// <returns>返回解压缩后的字符串</returns>
        public static string DecompressStringToString(string toDecompress)
        {
            if (!string.IsNullOrEmpty(toDecompress))
            {
                byte[] toDecompressBuffer = Convert.FromBase64String(toDecompress);

                using (MemoryStream decompressedStream = new MemoryStream())
                {
                    int len = BitConverter.ToInt32(toDecompressBuffer, 0);
                    decompressedStream.Write(toDecompressBuffer, 4, toDecompressBuffer.Length - 4);

                    byte[] outBuffer = new byte[len];

                    decompressedStream.Position = 0;
                    using (GZipStream gzip = new GZipStream(decompressedStream, CompressionMode.Decompress))
                    {
                        gzip.Read(outBuffer, 0, outBuffer.Length);
                    }

                    return Encoding.UTF8.GetString(outBuffer);
                }
            }
            else
            {
                return string.Empty;
            }
        }


        public static string J_Decompress(string param)//解压
        {
            string commonString = "";
            byte[] buffer = Convert.FromBase64String(param);
            MemoryStream ms = new MemoryStream(buffer);
            Stream sm = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(ms);
            //这里要指明要读入的格式，要不就有乱码
            StreamReader reader = new StreamReader(sm, System.Text.Encoding.Default);
            try
            {
                commonString = reader.ReadToEnd();
            }
            finally
            {
                sm.Close();
                ms.Close();
            }
            return commonString;
        }

        public static string Y_compress(string param)
        {
            string rStr = string.Empty;
           
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(param);
            MemoryStream ms = new MemoryStream(buffer, true);
            ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream sm = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms);
             
            try
            {
                byte[] FileData = new byte[(int)sm.Length];//创建缓冲数据 
                sm.Write(buffer, 0, buffer.Length);//写入压缩文件

                byte[] rbyte = new byte[ms.Length];
                ms.Read(rbyte, 0, rbyte.Length);

                Stream s = new MemoryStream(rbyte);
                StreamReader rader = new StreamReader(s, System.Text.Encoding.UTF8);
                  rStr = rader.ReadToEnd(); 
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                sm.Close();
                ms.Close();
            }
            return rStr;

        }



        /// <summary>
        /// 对字符串进行压缩
        /// </summary>
        /// <param name="str">待压缩的字符串</param>
        /// <returns>压缩后的字符串</returns>
        public static string CompressString(string str)
        {
            string compressString = "";
            byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
            byte[] compressAfterByte = Compress(compressBeforeByte);
            
            //compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
            compressString = Convert.ToBase64String(compressAfterByte);
            return compressString;
        }
        /// <summary>
        /// 对字符串进行解压缩
        /// </summary>
        /// <param name="str">待解压缩的字符串</param>
        /// <returns>解压缩后的字符串</returns>
        public static string DecompressString(string str)
        {
            string compressString = "";
            //byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
            byte[] compressBeforeByte = Convert.FromBase64String(str);
            byte[] compressAfterByte = Decompress(compressBeforeByte);
            compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
            return compressString;
        }


        /// <summary>
        /// 对byte数组进行压缩
        /// </summary>
        /// <param name="data">待压缩的byte数组</param>
        /// <returns>压缩后的byte数组</returns>
        public static byte[] Compress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
                zip.Write(data, 0, data.Length);
                zip.Close();
                byte[] buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Close();
                return buffer;

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        public static byte[] Decompress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(data);
                GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
                MemoryStream msreader = new MemoryStream();
                byte[] buffer = new byte[0x1000];
                while (true)
                {
                    int reader = zip.Read(buffer, 0, buffer.Length);
                    if (reader <= 0)
                    {
                        break;
                    }
                    msreader.Write(buffer, 0, reader);
                }
                zip.Close();
                ms.Close();
                msreader.Position = 0;
                buffer = msreader.ToArray();
                msreader.Close();
                return buffer;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }




        public static string yasuo(string compression)
        {
            MemoryStream ms = new MemoryStream();
            GZipOutputStream gzip = new GZipOutputStream(ms);
            byte[] binary = Encoding.UTF8.GetBytes(compression);
            gzip.Write(binary, 0, binary.Length);
            gzip.Close();
            byte[] press = ms.ToArray();
            string temp = Convert.ToBase64String(press);
           
            return temp;
        }

        public static string jieya(string Uncompression)
        {
            byte[] press = Convert.FromBase64String(Uncompression);
            GZipInputStream gzi = new GZipInputStream(new MemoryStream(press));
            MemoryStream re = new MemoryStream();
            int count = 0;
            byte[] data = new byte[4096];
            while ((count = gzi.Read(data, 0, data.Length)) != 0)
            {
                re.Write(data, 0, count);
            }
            byte[] depress = re.ToArray();
            string temp = Encoding.UTF8.GetString(depress);
           
            return temp;
        }


    }